package com.buffered.homework;

import java.io.*;

/**
 * @author げっしょく
 * @date 2021/8/3
 */
public class Test3 {
    public static void main(String[] args) throws IOException {
        /*
        3. 尝试用代码完成文件夹的复制（题目有点难，
        注意：不能直接使用IO流复制文件夹，IO流只能复制文件）
         */
        File f = new File("D:\\itheima\\资料\\JavaSE\\就业班作业");
        File f1 = new File("D:\\Java收获");
        CopeFile(f , f1);
    }

    private static void CopeFile(File f, File f1) throws IOException {
        File[] files = f.listFiles();
        if(files != null){
            for (File file : files) {
                if(file.isFile()){
                    String name = file.getAbsolutePath().substring(3);
                    String name1 = (f1.getAbsolutePath().endsWith("\\") ? f1.getAbsolutePath() : (f1.getAbsolutePath() + "\\") ) + name;
                    File file1 = new File(name1);
                    file1.createNewFile();
                    FileInputStream fis = null;
                    FileOutputStream fos = null;
                    try {
                        fis = new FileInputStream(file);
                        fos = new FileOutputStream(name1);
                        int len ;
                        byte[] b = new byte[1024];
                        while ((len = fis.read(b)) != -1) {
                            fos.write(b , 0 , len);
                        }
                        fos.flush();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        fis.close();
                        fos.close();
                    }
                }else{
                    String name = file.getAbsolutePath().substring(3);
                    String name1 = (f1.getAbsolutePath().endsWith("\\") ? f1.getAbsolutePath() : (f1.getAbsolutePath() + "\\") ) + name;
                    File file1 = new File(name1);
                    file1.mkdirs();
                    CopeFile(file , f1);
                }
            }
        }

    }
}
